import React, { useEffect, useCallback, useState } from 'react';
import { View3D } from 'react2-vtkjs-viewport';
import PropTypes from 'prop-types';
import classnames from 'classnames';

import './VTKViewport.styl';

const VTKViewport = props => {
  const style = { width: '100%', height: '100%', position: 'relative' };

  const { viewportIndex, activeViewportIndex, onContextMenu } = props;

  const [active, setActive] = useState(false);

  useEffect(() => {
    setActive(viewportIndex === activeViewportIndex);
  }, [viewportIndex, activeViewportIndex]);

  const setViewportActiveHandler = useCallback(() => {
    const { setViewportActive, viewportIndex, activeViewportIndex } = props;

    if (viewportIndex !== activeViewportIndex) {
      // set in Connected
      setViewportActive();
    }
  });

  const onDoubleClick = () => {
    if (props.onDoubleClick) {
      props.onDoubleClick(viewportIndex);
    }
  };

  useEffect(() => {
    const handleScrollEvent = evt => {
      const vtkViewportApiReference = props.onScroll(props.viewportIndex) || {};
      const viewportUID = vtkViewportApiReference.uid;
      const viewportWasScrolled = viewportUID === evt.detail.uid;

      if (viewportWasScrolled) {
        setViewportActiveHandler();
      }
    };

    window.addEventListener('vtkscrollevent', handleScrollEvent);
    return () =>
      window.removeEventListener('vtkscrollevent', handleScrollEvent);
  }, [props, props.onScroll, props.viewportIndex, setViewportActiveHandler]);

  return (
    <div
      className={classnames("vtk-viewport-handler", { active })}
      style={style}
      onClick={setViewportActiveHandler}
      onDoubleClick={onDoubleClick}
      onContextMenu={onContextMenu}
    >
      <View3D {...props} />
    </div>
  );
};

VTKViewport.propTypes = {
  setViewportActive: PropTypes.func.isRequired,
  viewportIndex: PropTypes.number.isRequired,
  activeViewportIndex: PropTypes.number.isRequired,
  /* Receives viewportIndex */
  onScroll: PropTypes.func,
  onDoubleClick: PropTypes.func,
};

VTKViewport.defaultProps = {
  onScroll: () => { },
};

export default VTKViewport;
